package cn.acyou.actions.convertJson;

import cn.acyou.utils.CommonUtil;
import cn.acyou.utils.MessageUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.wm.ToolWindow;
import org.yaml.snakeyaml.Yaml;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.io.File;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author youfang
 * @version [1.0.0, 2021/3/25]
 **/
public class MyTools {
    private JButton closeButton;
    private JButton copyButton;
    private JTextArea textArea;
    private JPanel myToolsContent;
    private JButton clearButton;

    private JTabbedPane tabbedPane1;
    private JPanel json_tool;
    private JButton url_encode;
    private JTextArea url_text;
    private JButton url_decode;
    private JButton base64_encode;
    private JButton base64_decode;
    private JButton format;

    private JButton propertiesYmlButton;
    private JButton ymlPropertiesButton;
    private JTextArea textArea3;


    public MyTools(ToolWindow toolWindow){
        //格式化
        format.addActionListener(e -> {
            String jsonString = textArea.getText();
            try {
                JsonParser jsonParser = new JsonParser();
                JsonObject jsonObject = jsonParser.parse(jsonString).getAsJsonObject();
                Gson gson = new GsonBuilder().setPrettyPrinting().create();
                String prettyStr = gson.toJson(jsonObject);
                textArea.setText(prettyStr);
            } catch (Exception ex) {
                ex.printStackTrace();
                Notification success = MessageUtil.notifyGroup.createNotification("字符串不是合法JSON！", NotificationType.INFORMATION);
                Notifications.Bus.notify(success, null);
            }
        });
        //关闭按钮
        closeButton.addActionListener(e -> toolWindow.hide(null));
        //清空按钮
        clearButton.addActionListener(e -> {
            textArea.setText("");
        });
        //复制按钮
        copyButton.addActionListener(e -> {
            //面板内容
            String text = textArea.getText();
            StringSelection selection = new StringSelection(text);
            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            clipboard.setContents(selection, selection);

            String message = "复制成功！";
            Notification success = MessageUtil.notifyGroup.createNotification(message, NotificationType.INFORMATION);
            Notifications.Bus.notify(success, null);
        });
        //绑定URL工具
        bindUrlTools();
        //绑定YML转换工具
        bindYmlPropertiesTools();
    }

    private void bindYmlPropertiesTools(){
        //yml转properties
        ymlPropertiesButton.addActionListener(e -> {
            final String text = textArea3.getText();
            try {
                new Yaml().load(text);
            }catch (Exception ex) {
                //ignore
                String message = "YAML格式不正确！";
                Notification success = MessageUtil.notifyGroup.createNotification(message, NotificationType.INFORMATION);
                Notifications.Bus.notify(success, null);
            }
            String s = CommonUtil.ymlToProperties(text);
            if (s.length() > 0){
                textArea3.setText(s);
            }
        });
        //properties转yml
        propertiesYmlButton.addActionListener(e -> {
            final String text = textArea3.getText();
            Map<String, String> propertiesMap = new LinkedHashMap<>();
            if (text != null && text.length() > 0){
                final String[] split = splitLineStr(text);
                if (split.length > 0) {
                    for (int i = 0; i < split.length; i++) {
                        String line = split[i];
                        if (line.startsWith("#")) {
                            continue;
                        }
                        final String[] splitline = line.split("=");
                        if (splitline.length == 2) {
                            String k = splitline[0];
                            String v = splitline[1];
                            propertiesMap.put(k, v);
                        }
                    }
                }
            }
            String sb = CommonUtil.propertiesToYml(propertiesMap);
            if (sb.length() > 0) {
                textArea3.setText(sb.toString());
            }
        });
    }

    private String[] splitLineStr(String str){
        String replace = str.replaceAll("\r\n", "\n");
        String replace2 = replace.replaceAll("\r", "\n");
        return replace2.split("\n");
    }

    /**
     * 绑定url工具 面板
     *
     */
    private void bindUrlTools(){
        url_encode.addActionListener(e -> {
            String text = url_text.getText();
            if (text != null && text.length() > 0){
                try {
                    String encodeText = URLEncoder.encode(text, "utf-8");
                    url_text.setText(encodeText);
                }catch (Exception exception){
                    exception.printStackTrace();
                }
            }
        });
        url_decode.addActionListener(e -> {
            String text = url_text.getText();
            if (text != null && text.length() > 0){
                String encodeText = null;
                try {
                    encodeText = URLDecoder.decode(text, "UTF-8");
                    url_text.setText(encodeText);
                } catch (Exception exception){
                    exception.printStackTrace();
                }
            }
        });
        base64_encode.addActionListener(e -> {
            String text = url_text.getText();
            if (text != null && text.length() > 0){
                String encodeText = Base64.getEncoder().encodeToString(text.getBytes());
                url_text.setText(encodeText);
            }
        });
        base64_decode.addActionListener(e -> {
            String text = url_text.getText();
            if (text != null && text.length() > 0){
                byte[] decode = Base64.getDecoder().decode(text.getBytes());
                url_text.setText(new String(decode));
                System.out.println(new String(decode));
            }
        });

    }

    public JPanel getContent() {
        return myToolsContent;
    }

    public void setContent(String content){
        textArea.setText(content);
    }
}
